package com.it.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.it.common.AppHttpCodeEnum;
import com.it.common.ErrorCode;
import com.it.model.LoginUser;
import com.it.model.User;
import com.it.utils.Assert;
import com.it.utils.Logs;
import com.it.utils.Pair;
import com.it.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {
//    @Autowired
//    private UserMapper userMapper;
//
//    @Autowired
//    private AccessMapper accessMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String userName) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUserName, userName);
        //User user = userMapper.selectOne(wrapper);
        //Assert.notNull(user, AppHttpCodeEnum.LOGIN_ERROR);

        List<User> users = new ArrayList<>();
        users.add(new User("panxiyi", passwordEncoder.encode("1515904c296caada87b72769f2ac9412")));
        users.add(new User("wangke", passwordEncoder.encode("1515904c296caada87b72769f2ac9412")));
        //Logs.common.info(Pair.of("users", JSON.toJSONString(users)));
        System.out.println(JSON.toJSONString(users));
        System.out.println(passwordEncoder.matches("123456!-", "$2a$10$lpjngHA4XgH5ltbOBMxZdOb.aNT8hJGBGK1ebFXHt8cmz.nHnW09a"));
        List<User> filterUsers = users.stream().filter(bo -> !StringUtils.isBlank(userName) && userName.equals(bo.getUserName())).collect(Collectors.toList());
        Assert.notNull(!filterUsers.isEmpty(), ErrorCode.LOGIN_ERROR);
        //List<String> permissions = accessMapper.selectPermissionsByUserId(user.getId());
        List<String> permissions = Arrays.asList("1","2");
        return new LoginUser(filterUsers.get(0), permissions);
    }

}
